/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.admin.entity.ElevatorPartsStructureTemplate;
import org.springblade.modules.admin.entity.ElevatorPartsStructureTemplateRelation;
import org.springblade.modules.admin.service.IElevatorPartsStructureTemplateRelationService;
import org.springblade.modules.admin.vo.ElevatorPartsStructureTemplateVO;
import org.springblade.modules.admin.mapper.ElevatorPartsStructureTemplateMapper;
import org.springblade.modules.admin.service.IElevatorPartsStructureTemplateService;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 电梯配件结构模板 服务实现类
 *
 * @author ysq
 * @since 2024-09-04
 */
@AllArgsConstructor
@Service
public class ElevatorPartsStructureTemplateServiceImpl extends BaseServiceImpl<ElevatorPartsStructureTemplateMapper, ElevatorPartsStructureTemplate> implements IElevatorPartsStructureTemplateService {

	private final IElevatorPartsStructureTemplateRelationService elevatorPartsStructureTemplateRelationService;

	@Override
	public IPage<ElevatorPartsStructureTemplateVO> selectElevatorPartsStructureTemplatePage(IPage<ElevatorPartsStructureTemplateVO> page, ElevatorPartsStructureTemplateVO elevatorPartsStructureTemplate) {
		return page.setRecords(baseMapper.selectElevatorPartsStructureTemplatePage(page, elevatorPartsStructureTemplate));
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean customEdit(ElevatorPartsStructureTemplate elevatorPartsStructureTemplate) {
		ElevatorPartsStructureTemplate template = getById(elevatorPartsStructureTemplate.getId());
		if (Func.isEmpty(template)) {
			throw new ServiceException("模板不存在");
		}

		if (Func.isBlank(elevatorPartsStructureTemplate.getCategoryArrIds())) {
			// 没配置类别，直接更新
			BeanUtil.copyProperties(elevatorPartsStructureTemplate, template, "categoryArrNames", "categoryArrIds");
			return updateById(template);
		} else {
			// 有配置类别，先校验重复，再更新模板，最后同步到所关联的梯
			if (!Func.isNull(checkRepeat(template.getId(), elevatorPartsStructureTemplate.getCategoryArrIds()))) {
				throw new ServiceException("已存在此结构类型");
			}
			BeanUtil.copyProperties(elevatorPartsStructureTemplate, template);
			if (updateById(template)) {
				List<ElevatorPartsStructureTemplateRelation> relationList = elevatorPartsStructureTemplateRelationService.list(Wrappers.<ElevatorPartsStructureTemplateRelation>lambdaQuery()
					.eq(ElevatorPartsStructureTemplateRelation::getStructureTemplateId, template.getId()));
				if (!Func.isEmpty(relationList)) {
					// 同步到关联的梯
					relationList.forEach(relation -> {
						relation.setCategoryArrIds(template.getCategoryArrIds());
						relation.setCategoryArrNames(template.getCategoryArrNames());
					});
					return elevatorPartsStructureTemplateRelationService.updateBatchById(relationList);
				}
				return true;
			}
		}

		return false;
	}

	/**
	 * 校验重复
	 * @param templateId 模板id,编辑时传入
	 * @param categoryArrIds 类别属性
	 * @return 重复: 重复的模板id，false：null
	 */
	@Override
	public Long checkRepeat(Long templateId, String categoryArrIds) {
		String newCategoryArrIds = strSplitSortHandler(categoryArrIds);
		List<ElevatorPartsStructureTemplate> allList = this.list();
		for (ElevatorPartsStructureTemplate elevatorPartsStructureTemplate : allList) {
			if (Func.isBlank(elevatorPartsStructureTemplate.getCategoryArrIds())) {
				continue;
			}
			String oldCategoryArrIds = strSplitSortHandler(elevatorPartsStructureTemplate.getCategoryArrIds());
			if (!Func.equalsSafe(templateId, elevatorPartsStructureTemplate.getId()) && Func.equalsSafe(oldCategoryArrIds, newCategoryArrIds)) {
				return elevatorPartsStructureTemplate.getId();
			}
		}
		return null;
	}

	/**
	 * 处理逗号分隔字符串，重新组合成新的有序字符串
	 * @param str
	 * @return
	 */
	private String strSplitSortHandler(String str) {
		List<String> strList = Arrays.asList(Func.split(str, ","));
		return strList.stream().sorted().collect(Collectors.joining("_"));
	}
}
